package org.tity.commons.environment;

 
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.tity.commons.io.EasyFile;

/**
 * @author fangjieli 
 * 目前局部支持Eclipase项目结构
 * */
public class ProjectInfo {
	public static void main(String[] args) {
		new ProjectInfo();
	}
	
	public ProjectInfo() {

		EasyFile eclipseClassPathFile = findProjectFile(".classpath");
		
		readEclipseClassPathFile(eclipseClassPathFile);

		System.out.println(eclipseClassPathFile.getAbsolutePath());
	}
	

	/**
	 * 读取 .classpath
	 * */
	private void readEclipseClassPathFile(EasyFile file) {
		if(file==null) {
			return;
		}
		SAXReader reader = new SAXReader();   
		Document doc = null;
		try {
			doc = reader.read(file.file());
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		Element root = doc.getRootElement();   
		Element foo; 
		List<Element> childElements = root.elements();
		//循环输出全部book的相关信息
		for (Element child : childElements) {
//          List<Element> books = child.elements();
			String kind=child.attribute("kind").getText();
			String path=child.attribute("path").getText();
			//获取当前元素名
            String name = child.getName();
            //获取当前元素值
            String text = child.getText();
            System.out.println(name + ":" + kind);
           
        }
		
		
	}

	private EasyFile findProjectFile(String filename) {
		EasyFile dir=PathTool.getDir(ProjectInfo.class);
		EasyFile file=null;
		while(true)
		{
			file=new EasyFile(dir.getAbsolutePath()+"/"+filename);
			if(file.exists()) {
				break;
			} else {
				file=null;
			}
			dir=dir.getParentFile();
			if(dir==null) {
				break;
			}
		}
		return file;
	}
	
	private static final String  CLASSES_KEY="/target/classes/";
	private static final String  TEST_CLASSES_KEY="/target/test-classes/";
 
	public static EasyFile getMavenSourceDir(Class clz)
	{
		EasyFile dir=PathTool.getDir(clz);
		String path=dir.getAbsolutePath();
		path=path.replace('\\', '/');
		String cata="";
		if(path.indexOf(CLASSES_KEY)!=-1)
		{
			cata="main";
		}
		else if(path.indexOf(TEST_CLASSES_KEY)!=-1)
		{
			cata="test";
		}
		
		path=path.replace(TEST_CLASSES_KEY, "/src/"+cata+"/java/");
		path=path.replace(CLASSES_KEY, "/src/"+cata+"/java/");
		dir=new EasyFile(path);
		
		if(!dir.exists()) {
			dir=PathTool.getDir(clz);
			path=dir.getAbsolutePath();
			path=path.replace('\\', '/');
			path=path.replace(CLASSES_KEY, "/src/");
			dir=new EasyFile(path);
		}
		if(!dir.exists()) {
			return null;
		}
		return dir;
	}
	
}
